package no.sogl.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class TeamContact {
	@NotNull
	@ManyToOne
    private Person contact;

	@NotNull
    @ManyToOne
    private Team team;
    
    @NotNull
    private boolean active = true;
    
	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "SS")
	@Column(updatable = false, insertable = true)
	private Date createdAt = new Date();

	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "S-")
	private Date joinedOn = new Date();

	@NotNull
	@Temporal(TemporalType.TIMESTAMP)
	@DateTimeFormat(style = "SS")
	private Date updatedAt = new Date();
	
    @Transactional
    public void persist() {
		if ( active)
			contact.addTag(team.getName());
		TeamContact.entityManager().persist(this);
    }
    
    @Transactional
    public TeamContact merge() {
    	updatedAt = new Date();
		if ( active)
			contact.addTag(team.getName());
		else
			contact.removeTag(team.getName());
		TeamContact merged = TeamContact.entityManager().merge(this);
        this.entityManager.flush();
        return merged;
    }
    
    @Transactional
    public void remove() {
    	contact.removeTag(team.getName());
    	EntityManager em = TeamContact.entityManager();
        if (em.contains(this)) {
            em.remove(this);
        } else {
        	TeamContact attached = TeamContact.findTeamContact(getId());
            em.remove(attached);
        }
    }

}
